﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Web;
using System.Web.Script.Serialization;
using System.Web.SessionState;
using Edge.Common.ComponentModel.Parameters;
using log4net;

namespace Shop.Web.AppCode.AjaxHandlers
{
    public abstract class BaseHandler : IRequiresSessionState
    {
        protected static readonly ILog log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);

        public string ProcessRequest(HttpContext context)
        {
            WebParameterAttribute.SetValues(this, context.Request);
            try
            {
                return Process(context);
            }
            catch (Exception ex)
            {
                log.Error("Ajax Handler Process Exception. Content: " + context.Request.QueryString["content"] + ".", ex);
                return JsonError("Access Denied!");
            }
        }

        protected virtual string Process(HttpContext context)
        {
            return Process();
        }

        protected abstract string Process();

        public static string JsonError(string errorText)
        {
            return string.Format("{{error: '{0}'}}", errorText.Replace("'", "\'"));
        }

        protected static string CreateJson(string name, string value)
        {
            return string.Format("{{{0}: '{1}'}}", name, value.Replace("'", "\'"));
        }

        public static string CreateJson(Dictionary<string, string> dictionary)
        {
            return new JavaScriptSerializer().Serialize(dictionary);
        }

        public static string CreateJson(Dictionary<string, object> dictionary)
        {
            return new JavaScriptSerializer().Serialize(dictionary);
        }
    }
}
